package com.example.utilcenter;

import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.v4.content.FileProvider;

import com.example.utilcenter.alertUtil.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class downLoadApk {


    public Uri getMyUri() {
        return myUri;
    }

    public void setMyUri(Uri myUri) {
        this.myUri = myUri;
    }

    private Uri myUri;

    /**
     * 下载最新版本
     */
    public void downloadAPK(final Context context, final String apkUrl, final String version, final String packName) {
        final ProgressDialog dialog = new ProgressDialog(context);
        dialog.setTitle("新版本下载中");
        dialog.setMessage("正在下载中，请稍等");
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgress(0);
        dialog.setMax(100);
        dialog.show();
        final Handler handle = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        dialog.setProgress(msg.arg1);
                        break;
                    case 1:
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                            ToastUtil.showSingleToast(context, "下载失败");
                        }
                        Process.killProcess(Process.myPid());
                        break;
                    case 2:
                        ToastUtil.showSingleToast(context, "请检查存储设置");
                        break;
                    case 3:
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Uri uri = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), (String) msg.obj));
                        installApk(context, uri, (String) msg.obj, packName);
                        break;
                }
//                super.handleMessage(msg);
            }
        };
        //开启子线程下载最新版本的apk
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = null;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/guoss V" + version + ".apk");
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            handle.sendEmptyMessage(2);
                            return;
                        }
                    }
                }
                InputStream in = null;
                FileOutputStream fos = null;
                try {
                    URL url = new URL(apkUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    long maxLenght = connection.getContentLength();
                    fos = new FileOutputStream(file);
                    in = connection.getInputStream();
                    int len = 0;
                    int size = 0;
                    byte[] buf = new byte[1024];
                    while ((size = in.read(buf)) != -1) {
                        len += size;
                        fos.write(buf, 0, size);
                        fos.flush();
                        Message msg = handle.obtainMessage();
                        msg.what = 0;
                        msg.arg1 = (int) (len * 100 / maxLenght);
                        handle.sendMessageDelayed(msg, 1000);
                    }
                    fos.close();
                    in.close();
                    Message message = handle.obtainMessage();
                    message.what = 3;
                    message.obj = file.getName();
                    handle.sendMessageDelayed(message, 1000);
                } catch (Exception e) {
                    handle.sendEmptyMessage(1);
                }
            }
        }).start();
    }

    /**
     * 打开安装apk
     */
    private void installApk(Context context, Uri apkUri, String obj, String packName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), obj);
            Uri contentUri = myUri;
            install.setDataAndType(contentUri, "application/vnd.android.package-archive");
            context.startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 如果不加上这句的话在apk安装完成之后点击单开会崩溃
            context.startActivity(install);
        }

        Process.killProcess(Process.myPid());
        ActivityManager activitymanager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        activitymanager.restartPackage(context.getPackageName());

    }


}
